package com.coding.service.impl;

import com.coding.dto.RestBean;
import com.coding.entity.Message;
import com.coding.entity.vo.MsgVO;
import com.coding.mapper.MessageMapper;
import com.coding.service.FollowService;
import com.coding.service.MessageService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Resource
    private MessageMapper messageMapper;

    @Resource
    private FollowService followService;

    @Resource
    private BlacklistServiceImpl blacklistService;


    /**
     * 判断是否可以发送消息
     *
     * @param senderId
     * @param receiverId
     * @return
     */
    public boolean canSendMessage(Long senderId, Long receiverId) {
        // 判断是否被拉黑
        if (blacklistService.isBlocked(senderId, receiverId)) {
            return false;
        }

        // 判断是否关注
        if (!followService.isFollowing(receiverId, senderId)) {
            int messageCount = messageMapper.getMessageCountBetweenUsers(senderId, receiverId);
//            return messageCount < 3;
            return true;
        }

        return true;
    }

    /**
     * 保存消息
     * @param message
     */
    public void saveMessage(MsgVO message) {
        messageMapper.insert(message);
    }

    /**
     * 获取消息
     * @param senderId
     * @param receiverId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public RestBean<List<Message>> getMessage(Long senderId, Long receiverId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Message> messagesBetweenUsers = messageMapper.getMessagesBetweenUsers(senderId, receiverId);
        if (messagesBetweenUsers != null) {
            return RestBean.success(messagesBetweenUsers);
        }

        return null;
    }

}

